package com.business.dashboard.interceptor;

import com.business.dashboard.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跨域预检请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        String uri = request.getRequestURI();
        log.debug("请求URI: {}", uri);

        // 管理员接口权限验证
        if (uri.startsWith("/api/admin") && !uri.contains("/auth/login")) {
            return validateAdminToken(request, response);
        }

        // 用户接口权限验证
        if (uri.startsWith("/api/users") && 
            !uri.contains("/register") && 
            !uri.contains("/login") && 
            !uri.contains("/check-")) {
            return validateUserToken(request, response);
        }

        return true;
    }

    /**
     * 验证管理员Token
     */
    private boolean validateAdminToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String token = getTokenFromRequest(request);
        
        // 尝试JWT token认证
        if (token != null) {
            try {
                // 验证是否为管理员token
                if (!jwtUtil.isAdminToken(token)) {
                    sendUnauthorizedResponse(response, "无效的管理员token");
                    return false;
                }

                // 验证token是否过期
                if (jwtUtil.isTokenExpired(token)) {
                    sendUnauthorizedResponse(response, "管理员token已过期");
                    return false;
                }

                // 获取管理员ID并设置到request中
                String adminId = jwtUtil.getAdminIdFromToken(token);
                request.setAttribute("adminId", Long.valueOf(adminId));
                
                log.debug("管理员JWT认证成功，adminId: {}", adminId);
                return true;
            } catch (Exception e) {
                log.error("管理员token验证失败", e);
                sendUnauthorizedResponse(response, "管理员token验证失败");
                return false;
            }
        }
        
        // 如果没有JWT token，尝试Session认证
        Object adminIdObj = request.getSession().getAttribute("adminId");
        if (adminIdObj != null) {
            Long adminId = (Long) adminIdObj;
            request.setAttribute("adminId", adminId);
            log.debug("管理员Session认证成功，adminId: {}", adminId);
            return true;
        }
        
        // 都失败则返回错误
        sendUnauthorizedResponse(response, "管理员token不能为空");
        return false;
    }

    /**
     * 验证用户Token
     */
    private boolean validateUserToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String token = getTokenFromRequest(request);
        
        if (token == null) {
            sendUnauthorizedResponse(response, "用户token不能为空");
            return false;
        }

        try {
            // 验证是否为用户token
            if (!jwtUtil.isUserToken(token)) {
                sendUnauthorizedResponse(response, "无效的用户token");
                return false;
            }

            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                sendUnauthorizedResponse(response, "用户token已过期");
                return false;
            }

            // 获取用户ID并设置到request中
            String userId = jwtUtil.getUserIdFromToken(token);
            request.setAttribute("userId", Long.valueOf(userId));
            
            log.debug("用户认证成功，userId: {}", userId);
            return true;
        } catch (Exception e) {
            log.error("用户token验证失败", e);
            sendUnauthorizedResponse(response, "用户token验证失败");
            return false;
        }
    }

    /**
     * 从请求中获取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return request.getParameter("token");
    }

    /**
     * 发送未授权响应
     */
    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"" + message + "\",\"data\":null}");
    }

}